import logging
import cgi
import datetime
import urllib
import webapp2
import jinja2
import os

from google.appengine.ext import db
from google.appengine.api import users

jinja_environment = jinja2.Environment(
                      loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
                    )

class DisplayTxtFolder(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'txt')
    logging.info('DisplayFolder.get(): path<%s>', path)
    list_o_files = os.listdir(path)
    template_values = {
      'list_o_files': list_o_files,
    }
    template = jinja_environment.get_template('txt.html')
    self.response.out.write(template.render(template_values))

class DisplayTxtFile(webapp2.RequestHandler):
  def get(self):
    # self.request.path[1:]: do not consider the first / in the request path
    # else the join will fail.
    path = urllib.unquote_plus(os.path.join(os.path.dirname(__file__), self.request.path[1:]))
    logging.info('DisplayTxtFile.get(): path<%s>', path)
    for line in open(path,'r').readlines():
      self.response.out.write(line)

class DisplayImagesFolder(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'images')
    logging.info('DisplayFolder.get(): path<%s>', path)
    list_o_files = os.listdir(path)
    template_values = {
      'list_o_files': list_o_files,
    }
    template = jinja_environment.get_template('images.html')
    self.response.out.write(template.render(template_values))

class DisplayJpgFile(webapp2.RequestHandler):
  def get(self):
    # self.request.path[1:]: do not consider the first / in the request path
    # else the join will fail.
    path = urllib.unquote_plus(os.path.join(os.path.dirname(__file__), self.request.path[1:]))
    logging.info('DisplayJpgFile.get(): path<%s>', path)
    # for line in open(path,'r').readlines():
    img = open(path,'rb').read()
    if not ".gif" or ".GIF" in path:
      self.response.headers['Content-Type'] = "image/jpeg"
    else:
      self.response.headers['Content-Type'] = "image/gif"
    self.response.out.write(img)

class MainPage(webapp2.RequestHandler):
  def get(self):
    logging.info('MainPage.get(): coucou')
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'url': url,
      'url_linktext': url_linktext
    }

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

myapp = webapp2.WSGIApplication([('/', MainPage),('/txt', DisplayTxtFolder),
                                  ('/txt/.*\.txt', DisplayTxtFile),
                                  ('/images', DisplayImagesFolder),
                                  ('/images/.*\.(?i)(?:jpg|gif)', DisplayJpgFile)],
                                debug=True)
